var express = require('express');
var router = express.Router();

// 引入mysql的Query
const Query = require("../tools/db")
// 加密字符
const { secret,signToken } = require("../config/config")

// mid
var { v4 } = require('uuid');
// 加密密码第三方模块
var md5 = require('md5');
// console.log(v4());//e0874021-6a8b-4d48-9dc6-4977c0ef568c
// console.log(  md5( md5( "password" +"{++—？？：：：—）（按时间安排进排气额派克服 是你福克斯}" ) )   );



// 注册
router.post("/register", async (req, res, next) => {
    let { username, password, password2 } = req.body

    if (!username) {
        next("请输入账号")
        return
    }
    if (!password) {
        next("请输入密码")
        return
    }
    if (!password2) {
        next("请再次输入密码")
        return
    }
    if (password != password2) {
        next("两次输入的密码不一致")
        return
    }


    // 此账号是否可注册
    let sql1 = `select *  from e_member where username="${username}"`
    let [err1, result1] = await Query(sql1)

    if (err1) {
        next(`注册失败请稍后再试`)
        return
    }

    if (result1.length != 0) {
        next("此用户名已被占用")
        return
    }

    // 执行注册
    // new Date().getTime()
    // Date.now()
    let md5password = md5(md5(password + secret))
    let sql2 = `insert into 
                    e_member(mid,username,password,createdate) 
                    values("${v4()}","${username}","${md5password}","${Date.now()}")`
    let [err2, result2] = await Query(sql2)

    if (err2) {
        next(`服务器出错了，请稍后再试`)
        return
    }


    res.send({
        status: 200,
        msg: "注册成功",
        result: result2.insertId
    })
})


// 登录 jwt 
router.post("/login", async (req, res, next) => {

    // 接收用户提交过来的信息
    let { username, password } = req.body

    // 判断是否传参
    if (!username) {
        next("请输入账号")
        return
    }
    if (!password) {
        next("请输入密码")
        return
    }



     // 查询是否可以登录
     let md5password = md5(md5(password + secret))
     let sql = `select *  from e_member where username="${username}" and password="${md5password}"`

     let [err, result] = await Query(sql)

     console.log(err, result);

     if (err) {
         next(`登录失败请稍后再试`)
         return
     }

     if(result.length==0){
         next("用户名或密码错误")
         return
     }


    //  需要有一个凭证，凭证上存储着能识别此用户的信息
    // 创建凭证jwt(jsonwebtoken)
    let token=signToken({username, mid:result[0].mid})

     res.send({
         status:200,
         msg:"登录成功",
         result:token
     })

})











module.exports = router;


// md5  专门用来给字符串加密的，常用于密码加密
